package com.liushao.controller;


import com.liushao.entity.BorrowInfo;
import com.liushao.result.Result;
import com.liushao.service.BorrowInfoService;
import com.liushao.util.JwtUtils;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author chen
 * @since 2025-01-03
 */
@RestController
@RequestMapping("/api/core/borrowInfo")
public class BorrowInfoController {

    @Autowired
    private BorrowInfoService borrowInfoService;


    //   .$get('/api/core/borrowInfo/auth/getBorrowAmount')
    //        .then((response) => {
    //          this.borrowAmount = response.data.borrowAmount

    @ApiOperation("获取借款额度")
    @GetMapping("/auth/getBorrowAmount")
    public Result getBorrowAmount(HttpServletRequest request){
        
        String token = null;
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies){
            if(cookie.getName().equals("token")){
                token = cookie.getValue();
                break;
            }
        }
        Long userId = JwtUtils.getUserId(token);
       // 只要是涉及到钱  用BigDecimal
        BigDecimal amount =borrowInfoService.getBorrowAmount(userId);

        return Result.ok().data("borrowAmount",amount);
    }



    //  http://localhost/api/core/borrowInfo/auth/getBorrowInfoStatus
    @GetMapping("/auth/getBorrowInfoStatus")
    public  Result getBorrowInfoStatus(HttpServletRequest request){

        
        String token = null;
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies){
            if(cookie.getName().equals("token")){
                token = cookie.getValue();
                break;
            }
        }
        Long userId = JwtUtils.getUserId(token);
        //通过用户的id获取用户的状态
       Integer status= borrowInfoService.getBorrowInfoStatus(userId);

        return  Result.ok().data("borrowInfoStatus",status);
    }


    //http://localhost/api/core/borrowInfo/auth/save

    @PostMapping("/auth/save")
    public Result save(@RequestBody BorrowInfo borrowInfo,HttpServletRequest request){
        
        String token = null;
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies){
            if(cookie.getName().equals("token")){
                token = cookie.getValue();
                break;
            }
        }        Long userId = JwtUtils.getUserId(token);

        borrowInfoService.saveBorrowInfo(borrowInfo,userId);

        return  Result.ok().message("提交成功");




    }
}

